package com.ccsoft.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

// 演示使用 ByteBuffer 数组读写
public class Ch08ByteBufferArray {
    public static void main(String[] args) throws IOException {
        // 创建 channel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress port = new InetSocketAddress(7001);

        // 绑定端口号
        serverSocketChannel.socket().bind(port);

        // 创建缓存数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        // 启动监听，等待客户端连接 - 有客户端连接则获取并返回该客户的 socket
        SocketChannel socketChannel = serverSocketChannel.accept();
        int length = 8;// 假设从客户端获取8个字节

        while(true){
            int byteRead = 0;
            while(byteRead < length){
                long readLength = socketChannel.read(byteBuffers);
                byteRead += readLength;
                System.out.println("读取的字节数量 byteRead：" + byteRead);

                // 打印前查看 position 和 limit
                Arrays.asList(byteBuffers).stream().map(buffer -> "position = " + buffer.position() + ",limit = " + buffer.limit()).forEach(System.out::println);
            }

            // 反转所有 buffer - 从读状态切换到写状态
            Arrays.asList(byteBuffers).stream().forEach(buffer -> buffer.flip());
            long byteWrite = 0;
            while(byteWrite < length){
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;
            }

            Arrays.asList(byteBuffers).forEach(buffer -> buffer.clear());
            System.out.println("byteRead = " + byteRead + " byteWrite = " + byteWrite +", messageLength = " + length);
        }
    }
}
